package distributed.lock.factory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

import distributed.lock.util.PropertiesUtil;

/**
 * @comment zk抽象类
 * @date 2015年11月10日 下午2:51:54
 * @author zhouxiao
 * @qq 772716714
 * @version 1.0
 */
public abstract class AbstractZookeeper implements Watcher {
	protected ZooKeeper zooKeeper = null;
	private static String ZK_IP = PropertiesUtil.get("zookeeper.ip");
	private static int ZK_PORT = Integer.parseInt(PropertiesUtil.get("zookeeper.port"));
	private static int ZK_TIMEOUT = Integer.parseInt(PropertiesUtil.get("zookeeper.timeout"));
	protected CountDownLatch countDownLatch = new CountDownLatch(1);

	// 连接zk
	public void connect() throws IOException, InterruptedException {
		zooKeeper = new ZooKeeper(ZK_IP + ":" + ZK_PORT, ZK_TIMEOUT, this);
		countDownLatch.await();
	}

	// zk处理
	public void process(WatchedEvent event) {
		if (event.getState() == KeeperState.SyncConnected) {
			countDownLatch.countDown();
		}
	}

	// 关闭集群
	public void close() throws InterruptedException {
		if (zooKeeper != null)
			zooKeeper.close();
	}

}
